package com.review.Demo_13_并发Queue;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.TimeUnit;


public class UseQueue {

	public static void main(String[] args) throws Exception {
		
		//高性能无阻塞无界队列：ConcurrentLinkedQueue
		
//		ConcurrentLinkedQueue<String> q = new ConcurrentLinkedQueue<String>();
//		q.offer("a");
//		q.offer("b");
//		q.offer("c");
//		q.offer("d");
//		q.add("e");
//		
//		System.out.println(q.poll());	//a 从头部取出元素，并从队列里删除
//		System.out.println(q.size());	//4
//		System.out.println(q.peek());	//b
//		System.out.println(q.size());	//4
		
		
		//阻塞队列---ArrayBlockingQueue有界
		ArrayBlockingQueue<String> array = new ArrayBlockingQueue<String>(8);//缓存长度为5---必须设置，没有无参构造方法
		boolean offer = array.offer("1",1, TimeUnit.SECONDS);//1秒内加不进去，就放弃
		array.put("a");
		array.put("b");
		array.add("c");
		array.add("f");
		System.out.println(array.offer("a", 3, TimeUnit.SECONDS));
		
		
		
		
		//阻塞队列---LinkedBlockingQueue无界
//		LinkedBlockingQueue<String> q1 = new LinkedBlockingQueue<String>();
//		q.offer("a");
//		q.offer("b");
//		q.offer("c");
//		q.offer("d");
//		q.add("e");
//		System.out.println(q.size());
//		
//		for (Iterator iterator = q.iterator(); iterator.hasNext();) {
//			String string = (String) iterator.next();
//			System.out.println(string);
//		}
//		
//		List<String> list = new ArrayList<String>();
//		System.out.println(q.drainTo(list, 3));//从队列中取3个元素放到集合中
//		System.out.println(list.size());
//		System.out.println(q.size());
//		for (String string : list) {
//			System.out.println(string);
//		}
		
		
		
		//阻塞队列---不支持缓存
//		SynchronousQueue<String> s = new SynchronousQueue<>();
//		s.add("a");
 		
		
		
		final SynchronousQueue<String> q = new SynchronousQueue<String>();
		
		//取元素
		Thread t1 = new Thread(new Runnable() {
			@Override
			public void run() {
				try {
					System.out.println(q.take());//queue中没有的话就阻塞在这
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		});
		
		
		//加元素
		Thread t2 = new Thread(new Runnable() {
			@Override
			public void run() {
				q.add("asdasd");
			}
		});
		
		//必须是先取元素后加元素
		t1.start();
		t2.start();
		
	}
}
